package com.eternal.advance;

import androidx.lifecycle.Observer;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eternal.advance.databinding.FragmentAdvanceBinding;
import com.eternal.advance.model.ItemModel;
import com.eternal.advance.model.AdvanceModel;
import com.eternal.base.IConnectAction;
import com.eternal.base.LogService;
import com.eternal.base.NotificationDialog;
import com.eternal.base.concat.BluetoothEvent;
import com.eternal.base.data.LogRepository;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.base.data.ble.BleStatue;
import com.eternal.base.global.ActivityEvent;
import com.eternal.base.global.BluetoothKey;
import com.eternal.base.protocol.ProtocolTransformer;
import com.eternal.base.router.RouterActivityPath;
import com.eternal.base.router.RouterFragmentPath;
import com.eternal.framework.binding.command.BindingConsumer;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.component.BaseFragment;
import com.eternal.framework.utils.KLog;
import com.eternal.framework.utils.Utils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator
 * On 2020/5/7
 * Description:
 *
 * @author Administrator
 */
@Route(path = RouterFragmentPath.Advance.PAGE_ADVANCE)
public class AdvanceFragment extends BaseFragment<FragmentAdvanceBinding, AdvanceModel> implements IConnectAction {
    public static final String ITEM_DELETE = "delete item";
    public static final String OPEN_NOTIFY = "openNotify";
    public static final String REFRESH_LOG = "refresh log";
    private MaterialDialog dialog;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_advance;
    }

    @Override
    public int initVariableId() {
        return BR.model;
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initMessenger();
        Intent intent = getActivity().getIntent();
        viewModel.init(RepositoryInjection.providerNotificationRepository(),
                intent.getStringExtra(ActivityEvent.DEVICE_MAC), intent.getByteExtra(ActivityEvent.DEVICE_PORT, (byte) 0x0), intent.getStringExtra(ActivityEvent.DEVICE_TIME));
    }

    @Override
    public void connected() {
        viewModel.start();
    }

    @Override
    public void disconnected() {
        viewModel.stop();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            viewModel.stop();
        } else {
            viewModel.updateAll();
            viewModel.start();
        }
    }

    private void initView() {
        viewModel.show.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                show(aBoolean);
            }
        });
//        binding.tvNotification.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Italic.ttf"));
//        binding.tvNotification.setLetterSpacing(0.04f);
    }

    private void initMessenger() {
        Messenger.getDefault().register(this, ITEM_DELETE, ItemModel.class, new BindingConsumer<ItemModel>() {
            @Override
            public void call(final ItemModel itemModel) {
                showDelete(itemModel);
            }
        });
        Messenger.getDefault().register(this, OPEN_NOTIFY, ItemModel.class, new BindingConsumer<ItemModel>() {
            @Override
            public void call(final ItemModel itemModel) {
                showNotify(itemModel);
            }
        });
    }

    private void show(boolean isShow) {
        if (isShow) {
            TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, -1f, Animation.RELATIVE_TO_SELF, 0f);
            animation.setDuration(500);
            binding.clAddAdvance.startAnimation(animation);
            binding.clAddAdvance.setVisibility(View.VISIBLE);
            binding.ivbAddProgram.setVisibility(View.GONE);
        } else {
            TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1f);
            animation.setDuration(500);
            binding.clAddAdvance.startAnimation(animation);
            binding.clAddAdvance.setVisibility(View.GONE);
            binding.ivbAddProgram.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("CheckResult")
    private void showNotify(ItemModel itemModel) {
//            LogService.getInstance().addRefresh(itemModel.model.mac, itemModel.model.port).subscribeOn(Schedulers.io());
        RxBus.getDefault().post(2L);
    }

    private void showDelete(final ItemModel item) {
        View view;
        if (dialog == null) {
            view = LayoutInflater.from(getContext())
                    .inflate(com.eternal.res.R.layout.reconfirm_dialog, null, false);
            dialog = new MaterialDialog.Builder(getContext())
                    .backgroundColor(0x00ffffff)
                    .customView(view, false)
                    .build();
            view.findViewById(com.eternal.res.R.id.tv_cancel)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
        }
        view = dialog.getCustomView();
        view.findViewById(com.eternal.res.R.id.tv_confirm)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        binding.listNotification.closeMenu();
                        viewModel.remove(item);
                        dialog.dismiss();
                    }
                });
        dialog.show();
    }

    @Override
    public void onDestroyView() {
        Messenger.getDefault().unregister(this);
        super.onDestroyView();
    }
}
